using AdmissionQA.Application.Common;
using AdmissionQA.Application.Dtos.ScholarshipInfo;
using AdmissionQA.Application.ServiceInterfaces;
using AdmissionQA.Domain.Entities;
using AdmissionQA.Domain.Repositorys;
using Microsoft.Extensions.Logging;

namespace AdmissionQA.Application.Services;

/// <summary>
/// 奖学金信息服务实现
/// </summary>
public class ScholarshipInfoServices(IRepository<ScholarshipInfo> repository, ILogger<ScholarshipInfoServices> logger, ITextEmbeddingService embeddingService)
    : IScholarshipInfoServices
{
    private readonly IRepository<ScholarshipInfo> _repository = repository;
    private readonly ILogger<ScholarshipInfoServices> _logger = logger;
    private readonly ITextEmbeddingService _embeddingService = embeddingService;

    /// <summary>
    /// 批量创建奖学金信息
    /// </summary>
    /// <param name="scholarshipInfos">奖学金信息列表</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateScholarshipInfosAsync(
        ScholarshipInfosDto scholarshipInfos
    )
    {
        var infosToCreate = scholarshipInfos
            .ScholarshipInfos.Select(item =>
                ScholarshipInfo.CreateScholarshipInfo(
                    item.ScholarshipName,
                    item.Amount,
                    item.Requirements
                )
            )
            .Where(item => item != null)
            .Select(item => item!)
            .ToList();

        if (infosToCreate.Count == 0)
        {
            _logger.LogWarning("批量创建奖学金信息失败：没有有效的信息");
            return Result<string>.Fail("没有有效的奖学金信息可以创建");
        }

        await _repository.CreateRangeAsync(infosToCreate);
        _logger.LogInformation("批量创建奖学金信息成功，数量：{Count}", infosToCreate.Count);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 创建奖学金信息
    /// </summary>
    /// <param name="scholarshipInfo">奖学金信息</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateScholarshipInfoAsync(ScholarshipInfoDto scholarshipInfo)
    {
        var info = ScholarshipInfo.CreateScholarshipInfo(scholarshipInfo.ScholarshipName, scholarshipInfo.Amount, scholarshipInfo.Requirements);
        if (info == null)
        {
            _logger.LogWarning("创建奖学金信息失败，参数：{@ScholarshipInfo}", scholarshipInfo);
            return Result<string>.Fail("创建奖学金信息失败");
        }
        var content = scholarshipInfo.ScholarshipName + " " + scholarshipInfo.Requirements + " " + (scholarshipInfo.Description ?? "");
        info.Embedding = _embeddingService.GetVector(content);
        await _repository.CreateAsync(info);
        _logger.LogInformation("创建奖学金信息成功，名称：{ScholarshipName}", scholarshipInfo.ScholarshipName);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 批量删除奖学金信息
    /// </summary>
    /// <param name="ids">奖学金信息ID列表</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteScholarshipInfosAsync(IEnumerable<Guid> ids)
    {
        // 并行获取所有奖学金信息
        var tasks = ids.Select(id => _repository.GetByIdAsync(id));
        var infos = await Task.WhenAll(tasks);

        // 过滤掉 null 值并转换为非空类型
        var validInfos = infos.OfType<ScholarshipInfo>().ToList();

        // 检查是否有有效的奖学金信息
        if (validInfos.Count == 0)
        {
            _logger.LogWarning("批量删除奖学金信息失败：未找到任何信息，ids={@Ids}", ids);
            return Result<string>.Fail("没有找到奖学金信息");
        }

        // 调用 Delete 方法标记为删除
        foreach (var info in validInfos)
        {
            if (!info.Delete())
            {
                _logger.LogWarning("批量删除奖学金信息时，信息已被删除，id={Id}", info.Id);
                return Result<string>.Fail($"奖学金信息 {info.Id} 已经被删除");
            }
        }

        // 更新所有有效的奖学金信息
        await _repository.UpdateRangeAsync(validInfos);
        _logger.LogInformation("批量删除奖学金信息成功，数量：{Count}", validInfos.Count);

        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 删除奖学金信息
    /// </summary>
    /// <param name="id">奖学金信息ID</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteScholarshipInfoAsync(Guid id)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            _logger.LogWarning("删除奖学金信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到奖学金信息");
        }
        if (!info.Delete())
        {
            _logger.LogWarning("删除奖学金信息失败：信息已被删除，id={Id}", id);
            return Result<string>.Fail("奖学金信息已经被删除");
        }
        await _repository.UpdateAsync(info);
        _logger.LogInformation("删除奖学金信息成功，id={Id}", id);
        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 根据ID获取奖学金信息
    /// </summary>
    /// <param name="id">奖学金信息ID</param>
    /// <returns>奖学金信息</returns>
    public async Task<Result<ScholarshipInfo>> GetScholarshipInfoByIdAsync(Guid id)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            return Result<ScholarshipInfo>.Fail("没有找到奖学金信息");
        }
        return Result<ScholarshipInfo>.Success(info);
    }

    /// <summary>
    /// 获取奖学金信息数量
    /// </summary>
    /// <returns>奖学金信息数量</returns>
    public async Task<int> GetScholarshipInfoCountAsync()
    {
        return await _repository.GetCountAsync();
    }

    /// <summary>
    /// 获取所有奖学金信息
    /// </summary>
    /// <returns>奖学金信息列表</returns>
    public async Task<Result<IEnumerable<ScholarshipInfo>>> GetAllScholarshipInfosAsync()
    {
        var infos = await _repository.GetAllAsync();
        return Result<IEnumerable<ScholarshipInfo>>.Success(infos);
    }

    /// <summary>
    /// 分页获取奖学金信息
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>分页结果</returns>
    public async Task<Result<IEnumerable<ScholarshipInfo>>> GetPagedScholarshipInfosAsync(
        int pageIndex = 0,
        int pageSize = 10
    )
    {
        var infos = await _repository.GetPagedAsync(pageIndex, pageSize);
        return Result<IEnumerable<ScholarshipInfo>>.Success(infos);
    }

    /// <summary>
    /// 根据名称搜索奖学金信息
    /// </summary>
    /// <param name="scholarshipName">奖学金名称</param>
    /// <returns>匹配的奖学金信息列表</returns>
    public async Task<Result<IEnumerable<ScholarshipInfo>>> SearchScholarshipInfosByNameAsync(
        string scholarshipName
    )
    {
        var infos = await _repository.GetListConditionAsync(item =>
            item.ScholarshipName.Contains(scholarshipName)
        );
        return Result<IEnumerable<ScholarshipInfo>>.Success(infos);
    }

    /// <summary>
    /// 更新奖学金信息
    /// </summary>
    /// <param name="id">奖学金信息ID</param>
    /// <param name="scholarshipInfo">奖学金信息</param>
    public async Task<Result<string>> UpdateScholarshipInfoAsync(Guid id, ScholarshipInfoDto scholarshipInfo)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            _logger.LogWarning("更新奖学金信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到奖学金信息");
        }
        info.UpdateScholarshipInfo(scholarshipInfo.ScholarshipName, scholarshipInfo.Amount, scholarshipInfo.Requirements, scholarshipInfo.Description);
        var content = scholarshipInfo.ScholarshipName + " " + scholarshipInfo.Requirements + " " + (scholarshipInfo.Description ?? "");
        info.Embedding = _embeddingService.GetVector(content);
        await _repository.UpdateAsync(info);
        _logger.LogInformation("更新奖学金信息成功，id={Id}", id);
        return Result<string>.Success("更新成功");
    }

    public async Task<Result<IEnumerable<ScholarshipInfo>>> SearchScholarshipInfosByEmbeddingAsync(string text, int topK = 5)
    {
        var queryEmbedding = _embeddingService.GetVector(text);
        var all = await _repository.GetAllAsync();
        var withScore = all.Where(x => x.Embedding != null)
            .Select(x => new { Entity = x, Score = CosineSimilarity(queryEmbedding, x.Embedding!) })
            .OrderByDescending(x => x.Score)
            .Take(topK)
            .Select(x => x.Entity)
            .ToList();
        return Result<IEnumerable<ScholarshipInfo>>.Success(withScore);
    }
    private static float CosineSimilarity(float[] v1, float[] v2)
    {
        if (v1 == null || v2 == null || v1.Length != v2.Length) return 0f;
        float dot = 0, norm1 = 0, norm2 = 0;
        for (int i = 0; i < v1.Length; i++)
        {
            dot += v1[i] * v2[i];
            norm1 += v1[i] * v1[i];
            norm2 += v2[i] * v2[i];
        }
        if (norm1 == 0 || norm2 == 0) return 0f;
        return dot / (float)(Math.Sqrt(norm1) * Math.Sqrt(norm2));
    }
}
